﻿using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RuoVea.ExDto;
using RuoVea.ExEnum;
using RuoVea.ExSugar;
using RuoVea.ExSugar.Entity;
using RuoVea.ExUtil;

namespace BookMarks.Web.Controllers;

[Authorize(Roles = "None")]
public class CategoryController : Controller
{
    /// <summary>
    /// 
    /// </summary>
    private readonly SugarRepository<BorCategory> _thisRepository;
    private readonly ICurrentUser _currentUser;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="thisRepository"></param>
    /// <param name="currentUser"></param>
    public CategoryController(SugarRepository<BorCategory> thisRepository, ICurrentUser currentUser)
    {
        _thisRepository = thisRepository;
        _currentUser = currentUser;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public IActionResult Index()
    {
        return View();
    }

    /// <summary>
    /// 查询所有/分页
    /// </summary>
    /// <returns></returns>
    [HttpPost("category/pages")]
    public async Task<RestfulResult<PageResult<CategoryDto>>> GetPagesAsync()
    {
        var restful = new RestfulResult<PageResult<CategoryDto>>() { Code = CodeStatus.OK};
        using var sr = new StreamReader(Request.Body);
        string dataStr = await sr.ReadToEndAsync();
        if (Request.Body.CanSeek)
            Request.Body.Position = 0;
        if (string.IsNullOrWhiteSpace(dataStr))
            throw new Exception("未提供上传数据。请在Request.Body中携带上传数据。");
        PageParam? data = JsonConvert.DeserializeObject<PageParam>(dataStr);
        data ??= new PageParam { PageNo = 1, PageSize = 2000 };
        restful.Data = new PageResult<CategoryDto>(1,2000) { };
        var query = await _thisRepository.AsQueryable()
             .Where(u => u.Creator == _currentUser.UserId)
            .OrderBy(u => u.Sort)
            .ToListAsync();

        var dataMenu = query.Adapt<List<CategoryDto>>();

        restful.Data.Rows = new TreeBuildUtil<CategoryDto>().Build(dataMenu);
        return restful;
    }
    /// <summary>
    /// 分页获取角色列表
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpGet("category/list")]
    public async Task<RestfulResult<List<CategoryDto>>> GetCategoryAsync([FromQuery] PageParam data)
    {
        RestfulResult<List<CategoryDto>> restfulResult = new() { Code = CodeStatus.OK };
        var query = await _thisRepository.AsQueryable()
            .Where(u => u.Creator == _currentUser.UserId)
            .OrderBy(u=>u.Sort)
            .ToListAsync();

        var dataMenu = query.Adapt<List<CategoryDto>>();
        restfulResult.Data = new TreeBuildUtil<CategoryDto>().Build(dataMenu);
        return restfulResult;
    }
    /// <summary>
    /// 新增
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpPost("category/add")]
    public async Task<RestfulResult> AddAsync([FromBody] BorCategory data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };

        var isExist = await _thisRepository.IsAnyAsync(u => (u.Name == data.Name || u.Code == data.Code) && u.Creator == _currentUser.UserId);
        if (isExist)
        {
            restful.Message = ErrorEnum.D3001.GetDescription(RuoVea.ExDto.Language.i18n.ResourceManager);
            return restful;
        }
        bool result = await _thisRepository.InsertAsync(data);
        if (result)
        {
            restful.Data = result;
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Message = "添加失败";
            return restful;
        }

    }
    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpPost("category/update")]
    public async Task<RestfulResult> UpdateAsync([FromBody] BorCategory data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };

        var isExist = await _thisRepository.IsAnyAsync(u => u.Id == data.Id && u.Creator == _currentUser.UserId);
        if (!isExist)
        {
            restful.Message = ErrorEnum.D3000.GetDescription(RuoVea.ExDto.Language.i18n.ResourceManager);
            return restful;
        }
        bool result = await _thisRepository.UpdateAsync(data);
        if (result)
        {
            restful.Data = result;
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Message = "修改失败";
            return restful;
        }
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpDelete("category/delete")]
    public async Task<RestfulResult> DeleteAsync([FromBody] EntityBaseId data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };

        if (data==null||data.Id == 0)
        {
            restful.Message = "删除失败";
            return restful;
        }
        bool isDelete = await _thisRepository.DeleteByIdAsync(data.Id);
        if (isDelete)
        {
            restful.Data = isDelete;
            restful.Message = "删除成功";
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Data = isDelete;
            restful.Message = "删除失败";
            return restful;
        }
    }
}
